<template>
  <div @viewappear="viewappear">
    <navbar title="商品分享" theme="light"></navbar>
    <list>
      <cell>
        <div class="tip" v-if="shareText">
          <text class="tip-text">分享文案已复制到剪贴板，请直接粘贴即可</text>
        </div>
      </cell>
      <cell>
        <div class="share-text-wrapper" v-if="shareText" @click="copyDesc()">
          <text class="share-text">{{shareText}}</text>
          <text class="share-text-copy-btn" >复制文案</text>
        </div>
        <div class="share-text-wrapper" v-if="shareTextKl" @click="copyKl">
          <text class="share-text">{{shareTextKl}}</text>
          <text class="share-text-tip">请不要分享口令到微信朋友圈，会被微信屏蔽，可以将口令发布到朋友圈的评论区里</text>
          <text class="share-text-copy-btn" >复制口令</text>
        </div>
      </cell>
      <cell>
        <image resize="contain" v-if="itemImgList.length <= 1" :src="picPreviewUrl"
               :style="{height: picPreviewHeight / 2 + 'px', width: picPreviewWidth / 2 + 'px'}"></image>
        <div class="img-list" v-if="itemImgList.length > 1" v-bind:key="rowIdx"
             v-for="(itemList, rowIdx) in itemImgRows">
          <div v-for="(img, idx) in itemList" v-bind:key="idx" class="item-img-wrap"
               :style="{width: imgWidth + 'px'}" :rowIdx="rowIdx" :idx="idx" @click="selectImg">
            <image v-if="img.src" :src="img.src" class="item-img" :style="{width: imgWidth + 'px', height: imgWidth + 'px'}"></image>
            <text v-if="img.src" :class="['icon', 'item-img-check-btn', img._checked && 'item-img-checked' ]">&#xe605;
            </text>
          </div>
        </div>
      </cell>
    </list>
    <div class="footer">
      <div class="share-btns">
        <div class="share-btn" v-if="false">
          <text class="share-btn-icon btn-wx icon activeable" to="pyq" @click="shareBtnClick">&#xe628;</text>
          <text class="share-btn-text">朋友圈</text>
        </div>
        <div class="share-btn" v-if="false">
          <text class="share-btn-icon btn-wx icon activeable" to="wxhy" @click="shareBtnClick">&#xe66a;</text>
          <text class="share-btn-text">微信好友</text>
        </div>
        <div class="share-btn">
          <text class="share-btn-icon btn-plain-img icon activeable" to="img" @click="savePlainImg">&#xe61d;</text>
          <text class="share-btn-text">保存图片</text>
        </div>
        <div class="share-btn">
          <text class="share-btn-icon btn-img icon activeable" to="img" @click="shareBtnClick">&#xe61d;</text>
          <text class="share-btn-text">单图分享</text>
        </div>
        <div class="share-btn">
          <text class="share-btn-icon btn-copy icon activeable" @click="copyKl">&#xe61f;</text>
          <text class="share-btn-text">复制口令</text>
        </div>
      </div>
    </div>
    <wxc-popup
        ref="shareImgPanel"
        :show="shareImgShown"
        @wxcPopupOverlayClicked="closeShareImgPanel"
        :height="shareImgPanelHeight"
        pos="bottom">
      <navbar title="生成图片" theme="light" :leftItemIcon="'\ue61b'"
              v-on:rightItemClick="saveImgToAlbum"
              rightItemText="保存" :leftBack="false"
              v-on:leftItemClick="closeShareImgPanel">
      </navbar>
      <image resize="contain" :src="picPreviewUrl" :style="{height: picPreviewHeight + 'px', width: picPreviewWidth + 'px'}"></image>
      <div>
        <scroller scroll-direction="horizontal" class="img-scroller" :style="{height: (scrollerImgWidth + 20) + 'px'}">
          <div v-for="(img, idx) in itemImgList" v-bind:key="idx" class="img-scroller-item"
               :style="{width: scrollerImgWidth + 'px', height: scrollerImgWidth + 'px'}" :idx="idx" @click="selectShareImg">
            <image v-if="img.src" :src="img.src" class="img-scroller-item-img"
                   :style="{width: scrollerImgWidth + 'px', height: scrollerImgWidth + 'px'}"></image>
            <text v-if="img.src" :class="['icon', 'item-img-check-btn', img._pic_checked && 'item-img-checked' ]">
              &#xe605;
            </text>
          </div>
        </scroller>
      </div>
      <div class="share-img-panel-footer">
        <div class="share-btns-sm">
          <div class="share-btn-sm" v-if="false">
            <text class="share-btn-sm-icon btn-wx icon activeable" to="pyq" @click="shareUBtnClick">&#xe628;</text>
            <text class="share-btn-sm-text">朋友圈</text>
          </div>
          <div class="share-btn-sm" v-if="false">
            <text class="share-btn-sm-icon btn-wx icon activeable" to="wxhy" @click="shareUBtnClick">&#xe66a;</text>
            <text class="share-btn-sm-text">微信好友</text>
          </div>
          <div class="share-btn-sm">
            <text class="share-btn-sm-icon btn-img icon activeable" to="img" @click="saveImgToAlbum">&#xe61d;</text>
            <text class="share-btn-sm-text">保存到相册</text>
          </div>
          <div class="share-btn">
            <text class="share-btn-sm-icon btn-copy icon activeable" @click="copyKl">&#xe61f;</text>
            <text class="share-btn-sm-text">复制口令</text>
          </div>
        </div>
      </div>
    </wxc-popup>
    <wxc-loading :show="loadingShown"></wxc-loading>
  </div>
</template>
<style lang="scss">
  @import "./sass/var";
  @import "./sass/mixin";
  @import "./sass/icon";
  @import "./sass/activeable";
  @import "./sass/buttons";

  .webview {
  }

  .img-scroller {
    flex-direction: row;
    background-color: #F9F9F9;
    padding: 10px 5px;
    @include border-top(1, solid, #ddd);
    &-item {
      margin: 0 5px;
      &-img {

      }
    }
  }

  .share-img-panel {
    position: relative;
    $bottom-height: 80px;
    position: relative;
    &-bottom {
      height: $bottom-height;
      flex-direction: row;
      align-items: stretch;
    }
    &-footer {
      padding-top: 10px;
    }
  }

  .share-img-panel-btn-save {
    background-color: #ccc;
    color: $color;
  }

  .tip {
    padding: 5px 10px;
    background-color: $brand-warning;
    color: #ffffff;
    align-items: center;
    &-text {
      color: #ffffff;
      font-size: 28px;
    }
  }

  .item-img-wrap {
    justify-content: center;
    align-items: center;
    position: relative;
  }

  .img-list {
    flex-direction: row;
    justify-content: space-between;
    padding: 0 20px 10px;
  }

  .item-img-check-btn {
    color: #ccc;
    transition: color .3s ease;
    font-size: 50px;
    position: absolute;
    right: 0;
    top: 0;
    text-align: center;
  }

  .item-img-checked {
    color: $color-primary;
  }

  .footer {
    padding: 10px 0;
    margin: 0 20px;
    @include border-top(1, solid, #ddd);
    &-title {
      color: $color-muted;
      font-size: 28px;
    }
  }

  .share-text {
    color: $color;
    font-size: 28px;
    &-wrapper {
      position: relative;
      @include border-bottom(1, solid, #ddd);
      padding: 10px 20px;
      margin-bottom: 10px;
    }
    &-tip {
      font-size: 24px;
      color: $color-warning;
    }
    &-copy-btn {
      color: $color-info;
      position: absolute;
      font-weight: 300;
      bottom: 10px;
      right: 20px;
      font-size: 28px;
    }
  }

  .share-btns {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
  }

  .share-btn {
    flex: 1;
    justify-content: center;
    align-items: center;
    &-icon {
      font-size: 60px;
      color: #ffffff;
      text-align: center;
      width: 100px;
      height: 100px;
      border-radius: 100px;
      line-height: 100px;
    }
    &-text {
      color: $color;
      margin-top: 10px;
      font-size: 28px;
    }
  }

  .share-btns-sm {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
  }

  .share-btn-sm {
    flex: 1;
    justify-content: center;
    align-items: center;
    &-icon {
      font-size: 60px;
      color: #ffffff;
      text-align: center;
      width: 100px;
      height: 100px;
      border-radius: 100px;
      line-height: 100px;
    }
    &-text {
      color: $color;
      margin-top: 5px;
      font-size: 24px;
    }
  }

  .btn-disabled {
    background-color: #eee;
    color: #aaa;
  }

  .btn-wx {
    background-color: #1FCB28;
  }

  .btn-qq {
    background-color: #43B1E9;
  }

  .btn-img {
    background-color: #A98264;
  }

  .btn-plain-img {
    background-color: #43B1E9;
  }

  .btn-copy {
    background-color: $brand-warning;
  }
</style>
<script>
  import {WxcLoading, WxcPartLoading, WxcPopup} from 'weex-ui'

  let queryparser = require('./include/queryparser')
let api = require('./include/api')
require('./include/page-xdom')
let grouping = require('./include/grouping')
let Deferred = require('Deferred')
let modal = weex.requireModule('modal')
let clipboard = weex.requireModule('clipboard')
let weixinApi = weex.requireModule('weixinApi')
let taobaoAuth = require('./include/taobao-auth')

module.exports = {
  mixins: [],
  components: {
    navbar: require('./components/navbar.vue'),
    WxcPopup,
    WxcLoading,
    WxcPartLoading
  },
  props: {
    id: {default: 0}
  },
  data () {
    return {
      // iosHide: weex.config.env.platform.toLowerCase() === 'ios',
      iosHide: false,
      item: {},
      shareInfo: {},
      shareText: '',
      shareTextKl: '',
      itemImgRows: [],
      itemImgList: [],
      imgWidth: (750 - 60) / 3,
      scrollerImgWidth: 750 / 4,
      selectedImgNum: 0,
      shareImgShown: false,
      shareImgPanelHeight: weex.config.env.deviceHeight * 750 / weex.config.env.deviceWidth,
      imgForShare: {},
      picPreviewHeight: 0,
      picPreviewWidth: 750,
      loadingShown: false,
      picPreviewUrl: '',
      id: 0,
      loaded: false
    }
  },
  created () {
    let cfg = this.$getConfig()
    let param = queryparser(cfg.bundleUrl)
    this.id = param.id || 0
    this.picPreviewHeight = weex.config.env.deviceHeight * 750 / weex.config.env.deviceWidth - this.imgWidth - 40 - 130 - 110
    this.loadingShown = true
    this.loadData()
  },
  methods: {
    loadData () {
      api.commissionItem.shareInfo({
        id: this.id
      }).done(rs => {
        let data = rs.data
        if (!data.shareInfo.taobaoRelationId && (data.item.ecomPlat === 'TAOBAO' || data.item.ecomPlat === 'TMALL')) {
          taobaoAuth.auth().done(rs => {
            if (data.authOk) {
              this.loadData()
            }
          })
          return
        }
        this.item = data.item
        this.itemImgRows = grouping(this.item.itemImgs, 3, (src, idx) => {
          let obj = {src: src, _checked: idx === 0, idx: idx}
          this.itemImgList.push(obj)
          obj._checked = true
          this.selectedImgNum += 1
          if (idx === 0) {
            obj._pic_checked = true
          }
          return obj
        }, {})
        this.imgForShare = this.itemImgList[0]
        this.shareInfo = data.shareInfo
        this.picPreviewUrl = api.url.commissionItem.sharePic({
          id: this.id,
          userId: data.shareInfo.userId,
          t: new Date().getTime()
        })
        this.loaded = true
        this.buildShareText()
      }).always(() => {
        this.loadingShown = false
      })
    },
    viewappear() {

    },
    onXRefresh (event) {
      this.onRefresh(event, Deferred.when())
    },
    buildShareText () {
      /**
         * 【天猫】心相印抽纸纸巾家用餐巾纸卫生纸实惠装家庭装心心相印旗舰店官网
         ---------------------------
         【券后价】41.9元
         【在售价】44.9元
         【下单链接】http://t.cn/RFNHlJs
         ---------------------------
         复制这条信息€bDQ2bWXx49l€，打开【手机淘宝】即可查看
         * */
      this.shareText = [
        '【' + this.shareInfo.ecomPlatTitle + '】' + this.shareInfo.title,
        '【券后价】' + this.shareInfo.price + '元' +
          '【在售价】' + this.shareInfo.originPrice + '元',
        // '【下单链接】' + this.shareInfo.shortUrl
      ].join('\n')
      if (this.shareInfo.kl) {
        this.shareTextKl = [
          '【券后价】' + this.shareInfo.price + '元' + '【在售价】' + this.shareInfo.originPrice + '元',
          // '【下单链接】' + this.shareInfo.shortUrl,
          '---------------------------',
          '复制这条信息' + this.shareInfo.kl + '，打开【手机淘宝】即可查看'
        ].join('\n')
      }
      clipboard.setString(this.shareText)
    },
    onLoadingMore (event) {
      this.loadingMore = true
    },
    gotoTop () {
      let dom = weex.requireModule('dom')
      dom.scrollToElement(this.$refs.topNode)
    },
    onPageScroll (event) {
      this.onPageScrollForScrollTop(event)
    },
    selectShareImg (e) {
      let idx = e.target.attr.idx
      this.imgForShare && (this.imgForShare._pic_checked = false)
      this.imgForShare = this.itemImgList[idx]
      this.imgForShare._pic_checked = true
      this.setSharePicImg(this.imgForShare.src)
    },
    selectImg (e) {
      let idx = e.target.attr.idx
      let rowIdx = e.target.attr.rowIdx
      let img = this.itemImgRows[rowIdx][idx]
      let checked = img._checked
      if (checked) {
        img._checked = false
        this.selectedImgNum -= 1
      } else {
        if (this.selectedImgNum >= 9) {
          modal.toast({message: '最多只能选择9张图片！', duration: 0.5})
          return
        }
        img._checked = true
        this.selectedImgNum += 1
      }
    },
    shareBtnClick: function (e) {
      let to = e.target.attr.to
      clipboard.setString(this.shareText)
      switch (to) {
        case 'img' :
          this.shareImgShown = true
          break
        case 'pyq':
          let images = []
          if (this.itemImgList.length > 1) {
            for (var i = 0; i < this.itemImgList.length; i++) {
              let itemImg = this.itemImgList[i]
              if (itemImg._checked) {
                images.push(itemImg.src)
              }
            }
          } else {
            images.push(this.picPreviewUrl)
          }
          if (images.length === 0) {
            modal.alert({message: '请选择需要分享的图片'})
            return
          }
          if (images.length === 1) {
            images[0] = api.url.commissionItem.sharePic({
              id: this.id,
              picUrl: encodeURIComponent(images[0]),
              userId: this.shareInfo.userId,
              t: new Date().getTime()
            })
          }
          weixinApi.sendTimeline({
            images: images,
            text: this.shareText
          }, flag => {
            if (!flag) {
              modal.alert({message: '您还没有安装微信，无法分享，请先安装微信！'})
            }
          })
          break
        case 'wxhy':
          let imagesWxhy = []
          for (var ii = 0; ii < this.itemImgList.length; ii++) {
            let itemImg = this.itemImgList[ii]
            if (itemImg._checked) {
              imagesWxhy.push(api.url.commissionItem.sharePic({
                id: this.id,
                picUrl: encodeURIComponent(itemImg.src),
                userId: this.shareInfo.userId,
                t: new Date().getTime()
              }))
            }
          }
          if (imagesWxhy.length === 0) {
            modal.alert({message: '请选择需要分享的图片'})
            return
          }
          if (imagesWxhy.length > 1) {
            modal.alert({message: '只能选择一张图片分享给微信好友！'})
            return
          }
          weixinApi.sendSession({
            images: imagesWxhy
          }, flag => {
            if (!flag) {
              modal.alert({message: '分享失败，请重试，如果您还没有安装微信，请先安装微信！'})
            }
          })
          break
      }
    },
    shareUBtnClick: function (e) {
      let to = e.target.attr.to
      clipboard.setString(this.shareText)
      switch (to) {
        case 'pyq':
          weixinApi.sendTimeline({
            images: [this.picPreviewUrl],
            text: this.shareText
          }, flag => {
            if (!flag) {
              modal.alert({message: '您还没有安装微信，无法分享，请先安装微信！'})
            }
          })
          break
        case 'wxhy':
          weixinApi.sendSession({
            images: [this.picPreviewUrl]
          }, flag => {
            if (!flag) {
              modal.alert({message: '您还没有安装微信，无法分享，请先安装微信！'})
            }
          })
          break
      }
    },
    closeShareImgPanel () {
      this.$refs.shareImgPanel.hide()
      setTimeout(() => {
        this.shareImgShown = false
      }, 200)
    },
    copyKl () {
      clipboard.setString(this.shareTextKl)
      modal.toast({message: '已为你复制口令', duration: 0.5})
    },
    copyDesc () {
      clipboard.setString(this.shareText)
      modal.toast({message: '已为你复制文案', duration: 0.5})
    },
    saveImgToAlbum () {
      let album = weex.requireModule('album')
      this.loadingShown = true
      album.saveUrl(this.picPreviewUrl, () => {
        this.loadingShown = false
        modal.toast({message: '保存成功', duration: 0.5})
        this.closeShareImgPanel()
      })
    },
    savePlainImg () {
      let images = []
      if (this.itemImgList.length > 1) {
        for (var i = 0; i < this.itemImgList.length; i++) {
          let itemImg = this.itemImgList[i]
          if (itemImg._checked) {
            images.push(itemImg.src)
          }
        }
      }
      if (images.length === 0) {
        modal.alert({message: '请选择需要保存的图片'})
        return
      }
      let album = weex.requireModule('album')
      this.loadingShown = true
      let self = this
      function doSave () {
        if (images.length === 0) {
          self.loadingShown = false
          modal.toast({message: '保存成功', duration: 0.5})
          return
        }
        album.saveUrl(images.pop(), () => {
          doSave()
        })
      }
      doSave()
    },
    setSharePicImg (url) {
      this.picPreviewUrl = api.url.commissionItem.sharePic({
        id: this.id,
        picUrl: encodeURIComponent(url),
        userId: this.shareInfo.userId,
        t: new Date().getTime()
      })
    }
  }
}
</script>
